<template>
  <label class="button image-upload-btn">
    上传图片
    <input type="file" accept="image/png,image/jpeg" @change="handleFileChange" hidden>
  </label>
</template>

<script setup lang="ts">
import { useElementStore } from '@/store'
import { ElementType, ImageFilter } from '@/types'

const elementStore = useElementStore()

// 处理图片上传
const handleFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return

  // 用FileReader将图片转为Base64
  const reader = new FileReader()
  reader.onload = (event) => {
    const base64 = event.target?.result as string
    // 添加图片元素到画布
    elementStore.addElement({
      type: ElementType.IMAGE,
      x: 400,
      y: 300,
      width: 200,
      height: 200,
      src: base64,
      filter: ImageFilter.NONE
    })
  }
  reader.readAsDataURL(file)

  // 重置input值，允许重复上传同一张图片
  input.value = ''
}
</script>

<style scoped>
.image-upload-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style>